#include "myserver.h"
#include <QTcpServer>
#include <QTcpSocket>
#include <QDebug>

MyServer::MyServer(QObject *parent)
    : QObject(parent),
      server(new QTcpServer)
{
    connect(server, &QTcpServer::newConnection,
            this, &MyServer::newConnectionSlot);
}

bool MyServer::startNet(quint16 port)
{
    if(getNetStatus())
        stopNet();
    return server->listen(QHostAddress::Any, port);
}

void MyServer::stopNet()
{
    server->close();
    //断开所有客户端
    foreach(SocketInfo *info, socketList)
    {
        info->socket->disconnectFromHost();
//        socket->abort(); 强制断开，不考虑后果
        delete info;
    }
    socketList.clear();
}

bool MyServer::getNetStatus()
{
    return server->isListening();
}

int MyServer::getClientNumber()
{
    return socketList.length();
}

void MyServer::sendDataToAllClient(const QByteArray &data)
{
    foreach(SocketInfo *info, socketList)
    {
        info->socket->write(data);
    }
}

void MyServer::sendDataToClient(const QByteArray &data, int des)
{
    foreach(SocketInfo *info, socketList)
    {
        if(info->index == des)
            info->socket->write(data);
    }
}

void MyServer::newConnectionSlot()
{
    //新客户端连接
    QTcpSocket *socket = server->nextPendingConnection();

    connect(socket, &QTcpSocket::readyRead,
            this, &MyServer::socketReadyReadSlot);
    connect(socket, &QTcpSocket::disconnected,
            this, &MyServer::socketDisconnectedSlot);
    SocketInfo *info = new SocketInfo;
    info->socket = socket;
    info->temp.clear();
    info->index = socket->socketDescriptor();
    socketList.append(info);
}

void MyServer::socketReadyReadSlot()
{
    QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
    QByteArray data;
    data.append(socket->readAll());
    foreach(SocketInfo *info, socketList)
    {
        if(info->socket == socket)
        {
            info->temp.append(data);
            while(true){
                //寻找左括号
                int i = 0;
                while(info->temp[i] != '{')
                {
                    i++;
                    if(i >= info->temp.length())
                        break;
                }
                if(i >= info->temp.length()){
                    info->temp.clear();
                    break;
                }
                else
                    info->temp = info->temp.mid(
                                i, info->temp.length());
                //匹配括号
                i = 0;
                int count = 0;
                while(i < info->temp.length())
                {
                    if(info->temp[i] == '{')
                        count++;
                    if(info->temp[i] == '}')
                    {
                        count--;
                        if(count == 0)
                        {
                            //发送找好的数
                            QByteArray buf = info->temp.mid(0, i+1);
//                            qDebug() << buf;
                            handleFrame(buf, info->index);
                            info->temp = info->temp.mid(i+1, info->temp.length());
                            i = 0;
                            break;
                        }
                    }
                    i++;
                }
                if(i >= info->temp.length())
                {
                    break;
                }

            }
        }
    }
}

void MyServer::socketDisconnectedSlot()
{
    QTcpSocket *socket = qobject_cast<QTcpSocket *>(sender());
    foreach(SocketInfo *info, socketList)
    {
        if(info->socket == socket)
        {
            socketList.removeOne(info);
            delete info;
            return;
        }
    }
}





